<template>
  <!-- Bu总费用分配 -->
  <view class="costsAssign">
    <div class="relative-wrap">
      <view class="costsAssign-header">
        <div class="title nowrap">{{ CompanyName }}</div>
        <div class="timer nowrap">{{ Year }}年{{ QuarterMap[QuarterId] }}</div>
      </view>
      <div class="costs-assign-header-con">
        <div class="cost-money-count">
          <div class="cost-money-count-item">
            <div class="row-item">
              <div class="u-flex">
                <div class="label-name">费用总金额：</div>
                <div class="price">￥ {{ form.TotalCost }}</div>
              </div>
            </div>
            <div class="row-item">
              <div class="u-flex">
                <div class="label-name">已分配金额：</div>
                <div class="price">￥ {{ form.ToCost }}</div>
              </div>
            </div>
            <div class="row-item">
              <div class="u-flex">
                <div class="label-name">可分配金额：</div>
                <div class="price">￥ {{ form.NoToCost }}</div>
              </div>
            </div>
          </div>
          <div class="cost-proportion">
            <!-- <div>使用比例</div>
            <div class="proportion-count">66.6%</div> -->
          </div>
        </div>
      </div>
    </div>
    <div class="costs-assign-item-con">
      <div class="cost-distribution-title">
        <span class="line"></span>
        费用分配
      </div>
      <div class="category-warp">
        <div class="category-warp-item" v-for="(item, index) in MarketMoney_Set_Detail_List" :key="index">
          <div class="category-warp-item-title">{{ item.Name }}</div>
          <div class="category-warp-item-con">
            <!-- <div v-if="IsPercentage == 1" class="u-flex u-m-t-20  u-p-l-20 u-p-r-20">
              <div class="u-flex-2">
                <u-input v-model="item.changeMoney" border="border" placeholder="请输入金额" />
              </div>
              <u-button class="u-m-l-20 u-m-r-20" style="height: 72rpx" @tap="handleAddMoney(item)">增加</u-button>
              <u-button style="height: 72rpx" @tap="handleReduceMoney(item)">减少</u-button>
            </div> -->
            <hr />
            <div class="cost-money-count-item">
              <div class="row-item">
                <div class="u-flex">
                  <div class="label-name">总金额：</div>
                  <div class="price">￥ {{ item.Money }}</div>
                </div>
              </div>
              <div class="row-item">
                <div class="u-flex">
                  <div class="label-name">当前剩余：</div>
                  <div class="price">￥ {{ getItemBalance(item) }}</div>
                </div>
              </div>
            </div>
            <div class="u-p-b-20 u-p-l-20">
              <u-collapse>
                <u-collapse-item title="展开详情">
                  <div class="u-flex" style="color: #333;line-height: 60rpx;">
                    <div class="u-flex-3 nowrap">分类</div>
                    <div class="u-flex-1 nowrap" v-if="IsPercentage == 1">比例</div>
                    <div class="u-flex-2 nowrap">分配总金额</div>
                    <div class="u-flex-2 nowrap">剩余金额</div>
                  </div>
                  <div
                    v-for="(sub, si) in item.Child_list"
                    :key="`s_${si}`"
                    class="u-flex u-row-center"
                    style="color: #333;line-height: 60rpx;"
                  >
                    <div class="u-flex-3 nowrap">{{ sub.Name }}</div>
                    <div class="u-flex-1 nowrap" v-if="IsPercentage == 1">{{ sub.Parent_Percentage }}%</div>
                    <div class="u-flex-2 nowrap" v-if="IsPercentage == 1">{{ getSubMoney(sub, item) }}</div>
                    <div class="u-flex-2 nowrap" v-else><u-input type="number" placeholder="金额"></u-input></div>

                    <div class="u-flex-2 nowrap">{{ getSubBalance(sub, item) }}</div>
                  </div>
                </u-collapse-item>
              </u-collapse>
            </div>
          </div>
        </div>
      </div>
    </div>

    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      show: false,
      list: [
        {
          value: '1',
          label: '比例'
        },
        {
          value: '2',
          label: '金额'
        }
      ],

      QuarterMap: {
        1: '第一季度',
        2: '第二季度',
        3: '第三季度',
        4: '第四季度'
      },

      CompanyName: '',
      Year: '',
      QuarterId: '',

      IsPercentage: '',

      MarketMoney_Set_List: [],
      MarketMoney_Set_Detail_List: [],

      showSubmit: '',

      form: {
        SetId: '',
        TotalCost: '',
        ToCost: '',
        NoToCost: '',
        Parent_List: [],
        All_List: []
      }
    };
  },

  onLoad(options) {
    if (options.Id) {
      this.form.SetId = options.Id;
    }

    uni.setNavigationBarTitle({
      title: '费用详情'
    });

    this.getData();
  },

  methods: {
    getSubMoney(sub, item) {
      if (this.IsPercentage == 1) {
        return Number(item.Money) * Number(sub.Parent_Percentage) * 0.01;
      } else {
        return Number(sub.Money);
      }
    },

    getSubBalance(sub, item) {
      return this.getSubMoney(sub, item) - Number(sub.CheckCost);
    },

    getItemBalance(item) {
      let total_assign = 0;

      if (item.Child_list) {
        item.Child_list.forEach(sub => {
          total_assign += Number(this.getSubMoney(sub, item));
        });
      }

      return Number(item.Money) - total_assign;
    },

    // 所有大区总金额之和不能大于费用总金额
    handleAddMoney(item) {
      if (!isNaN(item.changeMoney)) {
        if (Number(item.changeMoney) > Number(this.NoToCost)) {
          this.$u.toast('可分配金额不足');
          return false;
        }

        let total_money = 0;
        if (this.MarketMoney_Set_Detail_List) {
          this.MarketMoney_Set_Detail_List.forEach(t => {
            total_money += Number(t.Money);
          });
        }

        if (Number(total_money) + Number(item.changeMoney) > Number(this.form.TotalCost)) {
          this.$u.toast('所有大区总金额之和不能大于费用总金额');
          return false;
        }

        item.Money = Number(item.Money) + Number(item.changeMoney);

        this.form.ToCost = Number(this.form.ToCost) + Number(item.changeMoney);
      } else {
        this.$u.toast('请输入正确的金额数值');
      }
    },
    handleReduceMoney(item) {
      if (!isNaN(item.changeMoney)) {
        if (Number(item.Money) - Number(item.changeMoney) < 0) {
          this.$u.toast('大区总金额之和不能小于0');
          return false;
        }

        item.Money = Number(item.Money) - Number(item.changeMoney);

        this.form.ToCost = Number(this.form.ToCost) - Number(item.changeMoney);
      } else {
        this.$u.toast('请输入正确的金额数值');
      }
    },

    handleSubmit() {
      // 先把Child_list拍平，同时把Child_list的上级内容绑定到child_list的每一项中
      let subject_list = this.MarketMoney_Set_Detail_List.map(item => {
        item.Child_list.forEach(c => {
          c.Top = item;
        });
        return item.Child_list;
      }).flat();

      this.form.Parent_List = [];

      // 遍历所有大区的所有科目，若科目重复，则叠加金额，否则直接push到Parent_List中
      subject_list.forEach(item => {
        let exsit = this.form.Parent_List.find(s => s.Id == item.PId && s.TypeId == item.Id);

        if (exsit) {
          exsit.Money += Number(this.getSubMoney(item, item.Top));
        } else {
          this.form.Parent_List.push({
            Id: item.PId,
            TypeId: item.Id,
            Percentage: item.Parent_Percentage,
            Money: this.getSubMoney(item, item.Top)
          });
        }
      });

      this.form.All_List = this.MarketMoney_Set_Detail_List.map(item => {
        return {
          Id: item.Id,
          Money: item.Money,
          Child_list: item.Child_list.map(child => {
            return {
              BId: child.BId,
              Id: child.Id,
              Percentage: child.Parent_Percentage,
              Money: this.getSubMoney(child, item)
            };
          })
        };
      });

      this.$u.api.updateBuCosts(this.form).then(res => {
        const { ResultCode, ResultMessage } = res;

        if (ResultCode == 1) {
          this.$refs.uToast.show({
            title: ResultMessage,
            back: true
          });
        } else {
          this.$u.toast(ResultMessage);
        }
      });
    },

    getData() {
      this.$u.api
        .getBuCostsDetail({
          SetId: this.form.SetId
        })
        .then(res => {
          console.log(res);

          const {
            MarketMoney_Set_Detail_Child_List: MarketMoney_Set_Detail_List,
            MarketMoney_Set_List,
            ResultCode,
            ResultMessage,
            Submit_Show_Hide
          } = res;
          if (ResultCode == 1) {
            this.showSubmit = Submit_Show_Hide > 0;

            if (MarketMoney_Set_Detail_List) {
              MarketMoney_Set_Detail_List.forEach(item => {
                item.changeMoney = 0;
              });

              this.MarketMoney_Set_Detail_List = MarketMoney_Set_Detail_List;
            }
            if (MarketMoney_Set_List) {
              this.MarketMoney_Set_List = MarketMoney_Set_List;

              if (MarketMoney_Set_List.length > 0) {
                this.IsPercentage = MarketMoney_Set_List[0].IsPercentage;
                this.CompanyName = MarketMoney_Set_List[0].CompanyName;
                this.Year = MarketMoney_Set_List[0].Year;
                this.QuarterId = MarketMoney_Set_List[0].QuarterId;

                this.form.ToCost = MarketMoney_Set_List[0].ToCost;
                this.form.TotalCost = MarketMoney_Set_List[0].TotalCost;
                this.form.NoToCost = MarketMoney_Set_List[0].NoToCost;
              }
            }
          }
        });
    }
  }
};
</script>
<style>
page {
  background-color: #edeff2;
}
</style>
<style scoped lang="scss">
.costsAssign {
  margin: 0 20rpx;
  padding-top: 20rpx;
  // background: #ffffff;
  box-shadow: 0px 1px 3px rgba(101, 101, 101, 0.15);
  position: relative;
  height: 100vh;
  border-radius: 8px 8px 0px 0px;
  width: calc(100% -40rpx);
  .relative-wrap {
    position: fixed;
    box-shadow: 0px 1px 3px rgba(101, 101, 101, 0.15);
    z-index: 1000;
    background: #fff;
    width: calc(100% - 40rpx);
    padding-bottom: 20rpx;
    border-radius: 8px;
    .costsAssign-header {
      padding: 20rpx 20rpx;
      width: 100%;
      background: linear-gradient(90deg, #ff7626 -5.75%, #f7b66e 100%);
      border-radius: 8px 8px 0px 0px;
      display: flex;
      align-items: center;
      color: #fff;
      .title {
        flex: 2;
        font-size: 36rpx;
        font-weight: bold;
      }
      .timer {
        flex: 1;
        text-align: right;
        font-size: 28rpx;
      }
    }
    .costs-assign-header-con {
      width: 100%;
      padding-left: 25rpx;
      .cost-money-count {
        display: flex;
        align-items: center;
        .cost-money-count-item {
          flex: 2;
        }
        .cost-proportion {
          flex: 1;
          color: #ff7626;
          .proportion-count {
            font-size: 40rpx;
            font-weight: bold;
          }
        }
      }
    }
  }
  .costs-assign-item-con {
    margin-bottom: 100rpx;
    position: fixed;
    background: #fff;
    width: calc(100% - 80rpx);
    height: calc(100vh - 330rpx);
    overflow: auto;
    top: 330rpx;
    z-index: 100;
    font-size: 30rpx;
    padding: 0 20rpx 28rpx 20rpx;
    .cost-distribution-title {
      margin-top: 70rpx;
      display: flex;
      align-items: center;
      flex: 2;
      font-size: 36rpx;
      font-weight: bold;
      .line {
        display: inline-block;
        height: 36rpx;
        width: 6rpx;
        margin-right: 20rpx;
        background: #ff8441;
      }
    }
    .category-warp {
      margin-bottom: 200rpx;
      .category-warp-item {
        margin-top: 30rpx;
        background: #ffffff;
        box-shadow: 0px 1px 3px rgba(247, 181, 109, 0.3);
        border-radius: 8px;
        border-radius: 8px;
        border: 1px solid rgba(247, 181, 109, 0.3);
        .confirm-btn {
          margin-right: 30rpx;
          display: inline-block;
          width: 120rpx;
          text-align: center;
          line-height: 70rpx;
          background: #ff7626;
          color: #fff;
          border-radius: 10rpx;
          margin-left: 20rpx;
        }
        .category-warp-item-title {
          color: #ff8441;
          font-size: 32rpx;
          font-weight: bold;
          border-radius: 8px 8px 0px 0px;
          line-height: 80rpx;
          padding: 0 20rpx;
          border-bottom: 1px solid rgba(247, 181, 109, 0.2);
          background: rgba(247, 181, 109, 0.3);
        }
        .cost-money-count-item {
          display: flex;
          .row-item {
            margin-top: 26rpx;
            font-weight: bold;
            .label-name {
              text-align: right;
              font-weight: normal;
            }
          }
        }
      }
    }

    hr {
      margin: 28rpx 30rpx 0 30rpx;
      border: 1rpx dashed #b9b9b9;
    }
  }
  .costs-assign-btn-wrap {
    display: flex;
    align-items: center;
    position: fixed;
    bottom: 0;
    z-index: 99999;
    background: #fff;
    width: 100%;
    margin-left: -20rpx;
    padding: 10rpx 0;
    justify-content: space-between;
    .withdraw,
    .submit {
      width: 100%;
      text-align: center;
      line-height: 76rpx;
      border-radius: 38rpx;
    }
    .withdraw {
      color: #ff2723;
      border: 1px solid #ff2723;
    }
    .submit {
      background: #ff7626;
      color: #fff;
      margin: 0 60rpx;
    }
  }
  /deep/.u-collapse-head {
    padding-bottom: 0px;
  }
  /deep/.u-collapse-title {
    color: #ff7626;
  }
  .row-item {
    display: flex;
    margin-top: 16rpx;
    justify-content: space-between;
    font-weight: bold;
    .label-name {
      color: #979797;
      font-weight: normal;
      margin-left: 20rpx;
    }
  }
  .nowrap {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
